<?php
namespace App\Http\Controllers;

use App\Models\MyMessage;

use App\Models\Maker;

use App\Models\MakerUser;

use App\Http\Libs\Helper_Huanxin;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserInfoRequest;
use App\Models\RoleApply;
use App\Models\MakerApply;
use App\Models\RoleUser;
use App\Models\User;
use App\Models\UserCategory;
use App\Models\UserInfo;
use App\Models\UserInvestCategory;
use App\Models\UserProject;
use \DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Query\Builder;
use App\Models\Zone;
use App\Models\Category;
use App\Models\Notice;
use App\Models\Type;
class UserController extends CommonController
{

    /**
     * 显示前台用户列表
     *
     * @return Response
     */
    public function getIndex()
    {
        $users = User::with('roleUser.role')->orderBy('reg_time', 'desc')->orderBy('uid', 'asc')->paginate(10);

        return view('user.list')->with("users", $users)->with("actions", $this->actions);
    }

    /**
     * 执行一个搜索请求
     *
     */
    public function search(Request $request)
    {
        $data = $request->input();

        $sql = User::with('roleUser.role')->orderBy('reg_time', 'desc')->orderBy('uid', 'asc');
        if (isset($data['username']) && $data['username'] != '') {
            $sql->where('user.username', 'like', '%' . trim($data['username']) . '%');
        }

        if (isset($data['nickname']) && $data['nickname'] != '') {
            $sql->orWhere('user.nickname', 'like', '%' . trim($data['nickname']) . '%');
        }

        if (isset($data['realname']) && $data['realname'] != '') {
            $sql->orWhere('user.realname', 'like', '%' . trim($data['realname']) . '%');
        }

        if (isset($data['source']) && $data['source'] != '') {
            $sql->where('user.source', $data['source']);
        }

        if (isset($data['role']) && $data['role'] != '') {
            $uids = RoleUser::where('role_id', $data['role'])->lists('uid');
            $sql->whereIn('user.uid', $uids);
        }

        $users = $sql->paginate(10);

        return view('user.search')->with("users", $users)->with("username", trim($data['username']))
            ->with("nickname", trim($data['nickname']))->with("realname", trim($data['realname']))
            ->with("realname", $data['realname'])->with("source", $data['source'])
            ->with("actions", $this->actions)->with("role", $data['role']);
    }

    /**
     * 以表格形式显示单个前台用户资料详情，以便浏览
     *
     * @return Response
     */
    public function getInfo(Request $request)
    {
        $uid = $request->input('uid');
        $userInfo = User::with('roleUser.role', 'userInfo', 'userCategory.category', 'userInvestCategory', 'zone')->where('uid', '=', $uid)->first();
        $projects = UserProject::where('uid', '=', $uid)->get();

        return view('user.info')->with("userInfo", $userInfo)->with('projects', $projects);
    }

    /**
     * 以表单形式显示单个前台用户资料详情，以便修改
     *
     * @return Response
     */
    public function getEdit(Request $request)
    {
        $uid = $request->input('uid');

        $userInfo = User::with('roleUser.role', 'userInfo', 'userCategory.category', 'userInvestCategory', 'zone')->where('uid', '=', $uid)->first();
        $projects = DB::table('user_project')->where('uid', '=', $uid)->get();


        //用户关注的行业
        $userCategory = UserCategory::where('uid', $uid)->get();
        $userCategoryIds = $this->findCategoryIds($userCategory);

        //用户投资的行业
        $userInvestCategory = UserInvestCategory::where('uid', $uid)->get();
        $userInvestCategoryIds = $this->findCategoryIds($userInvestCategory);

        //用户投资轮次偏好
        $invest_project_period = array();
        $userInfo->invest_project_period!='' && $invest_project_period = explode(',', $userInfo->invest_project_period);
        $type = Type::with('sType')->where('code', 'project_period')->first();
        $types = array_column($type->sType->toArray(), 'name','code');
//        dd($types);

        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $family = familyTree($zones, $userInfo->zone_id);

        $lists = Category::all();

        return view('user.edit')->with("userInfo", $userInfo)->with('projects', $projects)->with('zoneTree', $zoneTree)->with('family', $family)
            ->with('lists', $lists)->with('userCategoryIds', $userCategoryIds)->with('invest_project_period', $invest_project_period)
            ->with('userInvestCategoryIds', $userInvestCategoryIds)->with('types', $types);
    }

    private function findCategoryIds($arr)
    {
        $ids = [];
        foreach ($arr as $k => $v) {
            $ids[] = $v->category_id;
        }

        return $ids;
    }

    /**
     * 更新某个前台用户资料详情
     *
     * @return Response
     */
    public function postEditInfo(UserInfoRequest $request)
    {
        $data = $request->input();
        if(isset($data['invest_project_period'])){
            $data['invest_project_period'] = implode(',', $data['invest_project_period']);
        }else{
            $data['invest_project_period'] = '';
        }
        if(isset($data['newPassword']) && $data['newPassword']!=''){
            $data['password'] = md5($data['newPassword']);
        }
        if($data['formType']=='investEdit'){
            $data['fund_min'] = 10000*$data['fund_min'];
            $data['fund_max'] = 10000*$data['fund_max'];
        }
        $fields = $this->assignFields($data);
        unset($fields['userFields']['uid']);
        unset($fields['userInfoFields']['uid']);

        User::where('uid', $data['uid'])->update($fields['userFields']);
        UserInfo::where('uid', $data['uid'])->update($fields['userInfoFields']);

        UserCategory::where('uid', $data['uid'])->delete();
        foreach ($data['followIndustry'] as $k => $v) {
            UserCategory::firstOrCreate(['uid' => $data['uid'], 'category_id' => $v]);
        }

        if (isset($data['investIndustry'])) {
            UserInvestCategory::where('uid', $data['uid'])->delete();
            foreach ($data['investIndustry'] as $k => $v) {
                UserInvestCategory::firstOrCreate(['uid' => $data['uid'], 'category_id' => $v]);
            }
        }

        return AjaxCallbackMessage('会员信息修改成功', true, url('user/index'));
    }

    /**
     * 获取创建会员时的身份选择页面
     */
    public function  getRoleSelect()
    {
        return view('user.roleselect');
    }

    public function postCreate(Request $request)
    {
        $this->validate($request, ['role' => 'required|in:2,3']);

        $data = $request->input();
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $lists = Category::all();

        $type = Type::with('sType')->where('code', 'project_period')->first();
        $types = array_column($type->sType->toArray(), 'name','code');

        if ($data['role'] == 2) {
            return view('user.createnormal')->with("lists", $lists)->with('zoneTree', $zoneTree);
        } else {
            return view('user.createinvest')->with("lists", $lists)->with('zoneTree', $zoneTree)->with('types', $types);
        }
    }

    /**
     * 创建一个用户
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postInsert(UserInfoRequest $request)
    {
        $data = $request->input();
        if(isset($data['invest_project_period'])){
            $data['invest_project_period'] = implode(',', $data['invest_project_period']);
        }else{
            $data['invest_project_period'] = '';
        }
        $data['password'] = md5($data['password']);
        $data['reg_time'] = strtotime('now');
        $data['last_time'] = strtotime('now');
        $data['source'] = 3;
        $data['reg_ip'] = getIp();
        isset($data['fund_min']) && $data['fund_min'] = 10000*$data['fund_min'];
        isset($data['fund_max']) && $data['fund_max'] = 10000*$data['fund_max'];
        $fields = $this->assignFields($data);

        $uResult = User::create($fields['userFields']);
        $fields['userInfoFields']['uid'] = $uResult->uid;
        $uiResult = UserInfo::create($fields['userInfoFields']);
        if ($data['formType'] == 'baseCreate') {
            $role_id = 2;
        } elseif ($data['formType'] == 'investCreate') {
            $role_id = 3;
        }
        $rResult = RoleUser::Create(['uid' => $uResult->uid, 'role_id' => $role_id]);

        foreach ($data['followIndustry'] as $v) {
            UserCategory::create(['uid' => $uResult->uid, 'category_id' => $v]);
        }

        if ($role_id == 3) {
            foreach ($data['investIndustry'] as $v) {
                UserInvestCategory::create(['uid' => $uResult->uid, 'category_id' => $v]);
            }
        }

        if (is_object($uResult) && is_object($uiResult) && is_object($rResult)) {
            return AjaxCallbackMessage('会员新增成功,新会员的uid为' . $uResult->uid, true, url('user/index'));
        } else {
            return AjaxCallbackMessage('会员新增失败,未知错误', false);
        }
    }

    /**
     * 用户申请角色升级列表
     *
     * @return Response
     */
    public function getApplyList()
    {
        $lists = RoleApply::with('user.roleUser.role', 'role')->orderBy('role_apply.created_at', 'desc')->orderBy('role_apply.status', 'asc')->paginate(10);

        return view('user.apply_list')->with("lists", $lists)->with("actions", $this->actions);
    }

    /**
     * 执行一个角色申请审核
     */
    public function applySearch(Request $request)
    {
        $data = $request->input();

        $sql = RoleApply::with('user.roleUser.role', 'role')->orderBy('role_apply.created_at', 'desc')->orderBy('role_apply.status', 'asc');

        if (isset($data['realname']) && $data['realname'] != '') {
            $uids = User::where('realname', 'like', '%' . $data['realname'] . '%')->orWhere('nickname', 'like', '%' . $data['realname'] . '%')->lists('uid');
            $sql->whereIn('uid', $uids);
        }

        if (isset($data['username']) && $data['username'] != '') {
            $uids = User::where('username', 'like', '%' . $data['username'] . '%')->lists('uid');
            $sql->whereIn('uid', $uids);
        }

        if (isset($data['reason']) && $data['reason'] != '') {
            $sql->where('reason', 'like', '%' . trim($data['reason']) . '%');
        }

        if (isset($data['apply_role']) && $data['apply_role'] != '') {
            $sql->where('role_id', $data['apply_role']);
        }

        if (isset($data['status']) && $data['status'] != '') {
            $sql->where('status', $data['status']);
        }
//        dd($this->actions);

        $lists = $sql->paginate(10);

        return view('user.applysearch')->with("lists", $lists)->with("username", trim($data['username']))
            ->with("realname", trim($data['realname']))->with("reason", trim($data['reason']))
            ->with("apply_role", $data['apply_role'])->with("status", $data['status'])
            ->with("actions", $this->actions);
    }

    /**
     * 单个用户申请角色审核页
     *
     * @return Response
     */
    public function getEditApply(Request $request)
    {
        $id = $request->input('id');

        $list = RoleApply::with('user.userInfo', 'role','maker.zone')->where('id', '=', $id)->first();
        $userInfo = User::with('roleUser.role')->where('user.uid', '=', $list->uid)->first();

        return view('user.edit_apply',["list"=> $list,'userInfo'=> $userInfo]);
    }

    /**
     * 审核某个用户角色申请
     *
     * @return Response
     */
    public function postEditApply(Request $request)
    {
        $this->validate($request, ['status' => 'required|in:-1,1',]);
        $data = $request->input();
        $user = User::where('uid', $data['uid'])->first();

        $firstRole = DB::table('role_user')->where('uid', $data['uid'])->first()->role_id;
        //投资人id
        $investor_id = config('system.investor');
        //创客空间
        $maker_id = config('system.maker');
        $roleId = $this->findRoleId($data['role']) + 1;
        $roleApply=RoleApply::where('id',$data['id'])->first();
        if ($data['status'] == -1) {
            RoleApply::where('id', $data['id'])->update(['status' => -1]);
            // 成为投资人失败反馈
            if ($data['status'] == -1 && $roleId == $investor_id) {
                //把偏好投资行业的表格数据删除
                UserInvestCategory::where('uid', $data['uid'])->delete();
                $content_sms = trans('sms.investorApplyFailure');
                @SendSMS($user->username, $content_sms, 'investorApplyFailure');
                $reason=$roleApply->reason?$roleApply->reason:'所提交的资料不完整或存在疑问。';

                $m_title='很抱歉您申请的投资人角色没有成功';
                $m_content='你于'.date('Y年m月d日',strtotime($roleApply->created_at)).'申请的“<span>投资人</span>”身份没有成功。';
                $m_ext='<p>失败原因：<span class="lightgray2">'.$reason.'</span></p>';
                MyMessage::createMessage($user->uid,$m_title,'official',$m_content,$m_ext,'');

            }
            //成为创客空间失败
            if ($roleId == $maker_id && $data['status'] == -1 && $firstRole != $maker_id) {
            	$reason=$roleApply->reason?$roleApply->reason:'所提交的资料不完整或存在疑问。';
                $content_sms = trans('sms.makerApplyFailure');
                @SendSMS($user->username, $content_sms, 'makerApplyFailure');
                $m_title='很抱歉您申请的创客空间没有成功';
                $m_content='你于'.date('Y年m月d日',strtotime($roleApply->created_at)).'申请的“<span>创客空间</span>”身份没有成功。';
                $m_ext='<p>失败原因：<span class="lightgray2">'.$reason.'</span></p>';
                MyMessage::createMessage($user->uid,$m_title,'official',$m_content,$m_ext,'');
            }
            return AjaxCallbackMessage('审核未通过,会员角色没有变化', true, url('user/apply-list'));
        }

        $result = DB::table('role_user')->where('uid', $data['uid'])->update(['role_id' => $roleId]);

        /***调用app接口刷新缓存***/
        $url = $this->wjtrUrl . "script/cache/refreshuserrole";
        $post = array('uid' => $data['uid']);
        @curl($url, $post);

        RoleApply::where('id', $data['id'])->update(['status' => 1]);

        //成为投资人成功
        if ($roleId == $investor_id && $data['status'] == 1 && $firstRole != $investor_id) {
            $content_sms = trans('sms.investorApplySuccess');
            @SendSMS($user->username, $content_sms, 'investorApplySuccess');
            $content_app = trans('app.investorApplySuccess', array('kefu' => getKefuName()));
            /***通知客户端刷新***/
            @Helper_Huanxin::sendMessage(array($user->uid), "已成功成为投资人", "admin", array("type" => "beInvestorSuccess_reload"));
            Notice::create(['title' => '欢迎成为投资人', 'content' => trans('webNotice.toBeInvestor.content'), 'type' => 1, 'uid' => $user->uid]);
            $m_title='恭喜您，申请的投资人角色已经通过审核';
            $m_content='你于'.date('Y年m月d日',strtotime($roleApply->created_at)).'申请的“投资人”身份通过无界投融审核并成功获得该身份。';
            $m_ext='<div class="mt10 mb10 dark2_gray">
	   	            <p>你已获得以下权限：</p>
	   	            <div class="lightgray2">
	   	  	        <p>① / 以投资人身份参与无界路演，尽揽无界投融优质项目</p>
	   	            <p>② / 开启直通车申请入口，可以申请成为直通车用户</p>
	   	            <p>③ / 定期获得无界投融项目、路演视频推送</p>
	   	            </div>
	                </div>
	                <div class="borderLine"></div>';
            MyMessage::createMessage($user->uid,$m_title,'official',$m_content,$m_ext,'');
        }
        return AjaxCallbackMessage('角色申请审核成功', true, url('user/apply-list'));
    }

    private function findRoleId($value)
    {
        $role = array('游客', '普通用户', '投资人', '创客空间');
        $result = array_search($value, $role);

        return $result;
    }

    private function assignFields(Array $array)
    {
        if ($array['business_card'] == '') {
            unset($array['business_card']);
        }

        $user = array('nickname', 'realname', 'status', 'email', 'is_ztc', 'password', 'username',
            'avatar', 'reg_time', 'last_time', 'source', 'reg_ip', 'zone_id', 'recommend', 'fund_min',
            'fund_max', 'invest_project_period');
        $userInfo = array(
            'sign',
            'address',
            'zipcode',
            'business_card',
            'introduction',
            'institution_name',
            'job',
            'tel',
            'fax',
            'office_zipcode',
            'office_address',
            'gender',
            'investCase',
        );
        $userFields = $userInfoFields = [];
        foreach ($array as $k => $v) {
            if (in_array($k, $user)) {
                $userFields[$k] = $v;
            } elseif (in_array($k, $userInfo)) {
                $userInfoFields[$k] = $v;
            }
        }

        return array('userFields' => $userFields, 'userInfoFields' => $userInfoFields);
    }
}